package net.borlis.errors.providers.implementation.filebase;

import net.borlis.errors.exceptions.ServerException;
import net.borlis.errors.exceptions.TranslatedException;
import net.borlis.errors.providers.common.IServerExceptionProcessor;
import net.borlis.errors.providers.common.ITranslatedExceptionProcessor;

import javax.annotation.PostConstruct;
import javax.enterprise.context.ApplicationScoped;
import javax.inject.Inject;
import java.util.HashSet;
import java.util.Locale;
import java.util.Set;
import java.util.logging.Logger;

/**
 * @author alex@borlis.net
 */
@ApplicationScoped @LocaleFileErrors
public class LocaleFileTranslatedExceptionProcessor implements ITranslatedExceptionProcessor {

    @Inject
    private ILocalMessageProvider messageProvider;

    @Inject @LocaleFileErrors
    private IServerExceptionProcessor exceptionProcessor;

    @Inject
    private Logger logger;

    @PostConstruct
    public void init() {
        logger.info("init bundles based translation");
    }

    @Override
    public TranslatedException newTranslatedException(String locale, ServerException se) {
        return new TranslatedException(se, messageProvider.getErrorMessage(locale, se.getKeyMaster()));
    }

    @Override
    public TranslatedException newTranslatedException(String locale, String code) {
        ServerException se = exceptionProcessor.newServerException(code);
        return new TranslatedException(se, messageProvider.getErrorMessage(locale, se.getKeyMaster()));
    }

    @Override
    public TranslatedException newTranslatedException(String locale, String code, Throwable cause) {
        ServerException se = exceptionProcessor.newServerException(code, cause);
        return new TranslatedException(se, messageProvider.getErrorMessage(locale, se.getKeyMaster()));
    }

    @Override
    public Set<String> getSupportedLocales() {
        Set<String> result = new HashSet<>();
        for (Locale locale: messageProvider.getSupportedLocales()) {
            result.add(locale.toString());
        }
        return result;
    }

}
